﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Auction_Intranet.Models;
using Auction_Intranet.Helpers;
using AuctionDataLayer;

namespace Auction_Intranet.Controllers
{
    [HandleError]
    public class BidsController : ParentController
    {
        DataRepository m_rep = new DataRepository();

        public ActionResult Index()
        {            
            var username = (User.Identity.Name).Split('\\')[1];
            var user = m_rep.GetUserByUsername(username);            
            if (user != null)
            {
                var result = m_rep.GetUserBidByUserId(user.Id);
                BidsListModel model = new BidsListModel();
                model.userBids = result;
                model.pendingBids = result.Where(x => x.StateId == 1).Count();
                model.acceptedBids = result.Where(x => x.StateId == 2).Count();
                model.declinedBids = result.Where(x => x.StateId == 3).Count();
                return View(model);
            }
            return View();
        }

        public ActionResult Delete(int? id)
        {
            if (id.HasValue)
            {
                int realId = id.Value;
                var model = m_rep.getBidById(realId);
                var username = (User.Identity.Name).Split('\\')[1];
                var user = m_rep.GetUserByUsername(username);
                if (model != null && user != null)
                {

                    ViewData["userId"] = user.MyGroupId;
                    return View(model);
                }
            }
            return View("NotFound");
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirm(int? id)
        {
            if (id.HasValue)
            {
                int realId = id.Value;
                var model = m_rep.getBidById(realId);
                var username = (User.Identity.Name).Split('\\')[1];
                var user = m_rep.GetUserByUsername(username);                
                //Delete bid
                if (model != null && user != null)
                {
                    var group = m_rep.GetGroupById(model.GroupId);
                    //if bid is personal
                    if (model.GroupId == user.MyGroupId)
                    {                        
                        UserInGroup userInGroup = m_rep.GetUserInGroupById(user.Id, user.MyGroupId);
                        UserInGroupBid userInGroupBid = m_rep.GetUserInGroupBidById(userInGroup.Id, model.Id);
                        Group myGroup = m_rep.GetGroupById(user.MyGroupId);
                        //amount to restore to user
                        var memberCreditPaid = userInGroupBid.MembersCreditPaid;
                        var realAmount = memberCreditPaid;
                        userInGroup.CreditAddedSpent -= realAmount;
                        if (userInGroup != null && userInGroupBid != null && model != null && myGroup != null)
                        {
                            //update UserInGroup credit spend
                            m_rep.UpdateUserInGroupBalance(userInGroup);
                            //update group balance
                            m_rep.UpdateGroupBalance(myGroup.Balance + realAmount, myGroup.Id);
                            //update user balance
                            m_rep.UpdateUserBalance(user.Balance + realAmount, user.Id);
                            //delete UserInGroupBid
                            m_rep.deleteUserInGroupBid(userInGroupBid);
                            //delete Bid
                            //If any room, delete all bids 
                            if (model.AnyRoom == true)
                            {
                                var allAnyBids = m_rep.getBidByIdForAnyRoom(realId);
                                m_rep.deleteAllBid(allAnyBids);
                            }
                            //Else delete single bid
                            else 
                            {
                                m_rep.deleteBid(model);
                            }                            
                            return RedirectToAction("Index");
                        }
                        return View("Error");                       
                    }
                    //Group bid
                    else {
                        IEnumerable<UserInGroup> usersInGroupList = m_rep.GetUsersInGroupById(model.GroupId);
                        IEnumerable<UserInGroupBid> usersInGroupBidList = m_rep.GetUserInGroupBidByIdOnly(model.Id);
                        var sumRefound = 0; 
                        foreach (var item in usersInGroupBidList)
                        {
                            var realAmount = item.MembersCreditPaid;
                            if (item.UserInGroup.ActiveMember == true)
                            {
                                sumRefound += realAmount;
                                var userIngroupItem = usersInGroupList.Where(x => x.Id == item.UserInGroupId).SingleOrDefault();
                                userIngroupItem.CreditAddedSpent -= realAmount;
                                //update UserInGroup credit spend
                                m_rep.UpdateUserInGroupBalance(userIngroupItem);
                            }
                            else
                            {
                                //update group balance
                                var personalGroupBalance = m_rep.GetGroupById(item.UserInGroup.User.MyGroupId);
                                m_rep.UpdateGroupBalance(personalGroupBalance.Balance + realAmount, item.UserInGroup.User.MyGroupId);
                                //update user balance
                                m_rep.UpdateUserBalance(item.UserInGroup.User.Balance + realAmount, item.UserInGroup.UserId);                            
                            }
                        }
                        //update group balance                        
                        m_rep.UpdateGroupBalance(group.Balance + sumRefound, group.Id);
                        //delete UserInGroupBidList
                        m_rep.deleteUserInGroupBidList(usersInGroupBidList);
                        //delete Bid
                        //If any room, delete all bids 
                        if (model.AnyRoom == true)
                        {
                            var allAnyBids = m_rep.getBidByIdForAnyRoom(realId);
                            m_rep.deleteAllBid(allAnyBids);
                        }
                        //Else delete single bid
                        else
                        {
                            m_rep.deleteBid(model);
                        }                            
                        return RedirectToAction("Index");
                    }                    
                }                
            }
            return View("NotFound");
        }
    }
}
